"""复制组件"""

from shutil import copyfile
import os.path as path
from case_convert import pascal_case


def read_lines(file_path):
    """读取文件"""
    with open(file_path, encoding="utf8") as file:
        return file.read().split("\n")


def write_lines(file_path, lines):
    """写文件"""
    with open(file_path, mode="w", encoding="utf8") as file:
        file.write("\n".join(lines))


def copy_comp(category, source, target):
    """复制组件"""
    for file in ["ts", "less", "spec.ts", "html"]:
        copy_comp_by_type(category, source, target, f".{file}")

    target_ts = "./src/app/" + get_comp_path_without_ext(category, target) + ".ts"
    lines = read_lines(target_ts)
    replace_selector(lines, source, target)
    replace_component_name(lines, source, target)
    write_lines(target_ts, lines)


def copy_comp_by_type(category, source, target, t):
    """复制组件的某一类型文件"""
    target_path = "./src/app/" + get_comp_path_without_ext(category, target) + t
    if path.exists(target_path):
        return

    source_path = "./src/app/" + get_comp_path_without_ext(category, source) + t
    if path.exists(source_path):
        copyfile(source_path, target_path)


def get_comp_path_without_ext(category, name):
    """取得组件完整路径
    >>> get_comp_full_path('button','basic')
    'button/button-basic.component

    >>> get_comp_full_path('button','basic-demo')
    'button/button-basic-demo.component
    """
    return f"{category}/{category}-{name}.component"


def replace_selector(lines, old_name, new_name):
    """替换组件selector"""
    for i, line in enumerate(lines):
        if line.strip().startswith("selector:"):
            lines[i] = line.replace(old_name, new_name)


def replace_component_name(lines, old_name, new_name):
    """替换组件名"""
    for i, line in enumerate(lines):
        if line.strip().startswith("export class"):
            old_name = pascal_case(old_name)
            new_name = pascal_case(new_name)
            lines[i] = line.replace(old_name, new_name)
